<template>
  <div class="task-manage">
    <div class="flex justify-between items-center mb-4">
      <h2>任务管理</h2>
      <el-button type="primary" @click="showCreateTaskDialog">创建任务</el-button>
    </div>

    <div class="mb-4">
      <el-radio-group v-model="taskFilter" size="small">
        <el-radio-button label="all">全部任务</el-radio-button>
        <el-radio-button label="incomplete">未完成任务</el-radio-button>
        <el-radio-button label="completed">已完成任务</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 添加加载中提示和空数据提示 -->
    <div v-if="loading" class="loading-state">
      <p>正在加载任务数据...</p>
    </div>
    <div v-else-if="tasks && tasks.length === 0 &&!loading" class="empty-state">
      <p>暂无任务数据</p>
    </div>

    <el-table :data="tasks" style="width: 100%" border v-else>
      <!-- 任务ID列添加排序功能 -->
      <el-table-column
          prop="id"
          label="任务ID"
          align="center"
          :sortable="true"
          :default-sort="{ prop: 'id', order: 'descending' }"
          @sort-change="handleSortChange">
      </el-table-column>
      <el-table-column prop="name" label="任务名称" align="center"></el-table-column>
      <el-table-column prop="description" label="任务描述" align="center"></el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.completed? 'success' : 'warning'">
            {{ scope.row.completed? '已完成' : '未完成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属角色" align="center">
        <template #default="scope">
          <el-tag type="info"
                  v-if="!scope.row.roles || scope.row.roles.length === 0 ||
                       scope.row.roles.every(r =>!r.id ||!(r.nameZh || r.name))">
            未分配角色
          </el-tag>
          <el-tag v-else
                  v-for="role in scope.row.roles.filter(r => r.id && (r.nameZh || r.name))"
                  :key="role.id"
                  type="info"
                  style="margin-right: 4px">
            {{ role.nameZh || role.name || '未知角色' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
              size="mini"
              @click="assignTaskToRole(scope.row)">
            分配角色
          </el-button>
          <el-button
              size="mini"
              type="primary"
              @click="markTaskCompleted(scope.row)"
              :disabled="scope.row.completed ||!scope.row.roles || scope.row.roles.length === 0">
            标记完成
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalTasks"
    >
    </el-pagination>

    <!-- 创建任务对话框 -->
    <el-dialog title="创建任务" v-model="createTaskDialogVisible" width="30%">
      <el-form :model="newTask" label-width="100px">
        <el-form-item label="任务名称" :rules="[{ required: true, message: '请输入任务名称', trigger: 'blur' }]">
          <el-input v-model="newTask.name" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input type="textarea" v-model="newTask.description" rows="3" placeholder="请输入任务描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createTaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createTask">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配任务给角色对话框 -->
    <el-dialog title="分配任务给角色" v-model="assignTaskDialogVisible" width="40%">
      <div>
        <h3>{{ currentTaskForAssign.name || '未选择任务' }}</h3>
        <el-form label-width="80px">
          <el-form-item label="选择角色">
            <el-select
                v-model="selectedRoleId"
                multiple
                filterable
                remote
                reserve-keyword
                placeholder="请选择角色"
                @remote-method="searchRoles"
                :remote="true"
                :loading="roleLoading"
                style="width: 100%">
              <el-option
                  v-for="role in filteredRoles"
                  :key="role.id"
                  :label="role.nameZh || role.name"
                  :value="role.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignTaskDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssignTask">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, watchEffect, nextTick } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";

// 假设这里从全局获取当前用户的角色ID，实际应用中按需调整获取方式
const currentRoleId = ref(1);

// 任务列表状态
const tasks = ref([]);
const taskFilter = ref('all'); // all, incomplete, completed
const loading = ref(false); // 加载状态标识

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalTasks = ref(0);

// 排序相关
const sortField = ref('id');       // 当前排序字段
const sortOrder = ref('descending'); // 当前排序顺序：ascending/descending/null

// 创建任务状态
const createTaskDialogVisible = ref(false);
const newTask = ref({ name: '', description: '', completed: false });

// 分配任务状态
const assignTaskDialogVisible = ref(false);
const currentTaskForAssign = ref({});
const selectedRoleId = ref([]);
const filteredRoles = ref([]);
const roleLoading = ref(false);

/**
 * 加载任务列表
 * @param {number} page - 当前页码
 * @param {number} size - 每页数量
 * @param {boolean} forceUpdate - 是否强制更新视图
 * @param {object} sort - 排序参数 { field, order }
 */
const loadTasks = async (page = 1, size = 10, forceUpdate = false, sort = {}) => {
  loading.value = true;
  currentPage.value = page;
  pageSize.value = size;

  // 合并排序参数
  const { field = sortField.value, order = sortOrder.value } = sort;
  sortField.value = field;
  sortOrder.value = order;

  try {
    let url = '';
    if (taskFilter.value === 'all') {
      // 调用新添加的查询全部任务接口
      url = `/tasks?page=${page}&pageSize=${size}`;
      // 添加排序参数
      if (field) {
        url += `&sortField=${field}&sortOrder=${order}`;
      }
    } else {
      // 原有的按角色筛选接口
      url = `/role/${currentRoleId.value}/tasks`;
      if (taskFilter.value === 'incomplete') {
        url = `/role/${currentRoleId.value}/tasks/incomplete`;
      } else if (taskFilter.value === 'completed') {
        url = `/role/${currentRoleId.value}/tasks/completed`;
      }
      url += `?page=${page}&pageSize=${size}`;
      // 添加排序参数
      if (field) {
        url += `&sortField=${field}&sortOrder=${order}`;
      }
    }

    console.log('请求URL:', url);
    const res = await request.get(url);
    console.log('响应数据:', res);

    if (res.code === 200) {
      // 兼容不同后端数据结构（处理records/list/data等字段）
      let taskList = [];
      if (res.data.records) {
        taskList = res.data.records;
      } else if (res.data.list) {
        taskList = res.data.list;
      } else if (Array.isArray(res.data)) {
        taskList = res.data;
      } else {
        console.error('数据格式异常，未找到任务列表字段');
        taskList = [];
      }

      // 深度处理任务数据，确保roles字段结构正确
      const processedTasks = taskList.map(task => {
        const roles = Array.isArray(task.roles) ? task.roles : [];
        // 利用Set对角色ID去重
        const uniqueRoleIds = [...new Set(roles.map(r => r?.id))];
        // 根据去重后的ID重新构建角色数组
        const uniqueRoles = uniqueRoleIds.map(id => roles.find(r => r?.id === id));
        return {
          ...task,
          roles: uniqueRoles
        };
      });

      console.log('更新后的任务数据:', processedTasks);

      // 使用深拷贝强制更新视图
      if (forceUpdate) {
        tasks.value = JSON.parse(JSON.stringify(processedTasks));
      } else {
        tasks.value = [...processedTasks];
      }

      // 兼容不同后端数据结构的total字段
      if (res.data.total !== undefined) {
        totalTasks.value = res.data.total;
      } else if (res.data.count !== undefined) {
        totalTasks.value = res.data.count;
      } else {
        totalTasks.value = processedTasks.length;
      }
    } else {
      ElMessage.error(res.message || '获取任务列表失败');
      tasks.value = [];
      totalTasks.value = 0;
    }
  } catch (error) {
    console.error('获取任务列表出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
    tasks.value = [];
    totalTasks.value = 0;
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadTasks();
});

/**
 * 处理排序变化
 * @param {object} sort - 排序信息 { prop, order }
 */
const handleSortChange = (sort) => {
  if (sort.prop) {
    // 有排序字段时，按新的排序条件加载数据
    loadTasks(currentPage.value, pageSize.value, false, {
      field: sort.prop,
      order: sort.order
    });
    console.log(`切换排序：字段=${sort.prop}，顺序=${sort.order}`);
  } else {
    // 无排序时，重置排序状态并加载数据
    loadTasks(currentPage.value, pageSize.value, false, {
      field: '',
      order: null
    });
    console.log('取消排序，加载默认顺序数据');
  }
};

// 创建任务
const showCreateTaskDialog = () => {
  newTask.value = { name: '', description: '', completed: false };
  createTaskDialogVisible.value = true;
};

const createTask = async () => {
  try {
    const res = await request.post('/task', newTask.value);
    if (res.code === 200) {
      ElMessage.success("创建任务成功");
      await loadTasks(currentPage.value, pageSize.value);
      createTaskDialogVisible.value = false;
    } else {
      ElMessage.error(res.message || '创建任务失败');
    }
  } catch (error) {
    console.error('创建任务出错:', error);
    ElMessage.error('网络请求失败，请检查控制台日志');
  }
};

// 分配任务给角色
const assignTaskToRole = (task) => {
  if (!task.id) {
    ElMessage.error('任务数据不完整，无法分配角色');
    return;
  }

  // 初始化当前任务数据，确保包含必要字段
  currentTaskForAssign.value = {
    ...task,
    roles: task.roles || [],
    roleIds: task.roleIds || []
  };

  // 预填充已分配的角色
  selectedRoleId.value = [...currentTaskForAssign.value.roleIds];
  filteredRoles.value = [];
  assignTaskDialogVisible.value = true;
  searchRoles('');
};

const searchRoles = async (query) => {
  if (!query) query = '';
  roleLoading.value = true;

  try {
    const res = await request.get(`/roles?search=${encodeURIComponent(query)}`);
    console.log('搜索角色响应:', res);

    if (res.code === 200) {
      let roleList = [];

      // 兼容不同的后端数据结构
      if (Array.isArray(res.data)) {
        roleList = res.data;
      } else if (res.data && Array.isArray(res.data.list)) {
        roleList = res.data.list;
      } else if (res.data && Array.isArray(res.data.records)) {
        roleList = res.data.records;
      } else {
        console.error('角色数据格式不符合预期:', res.data);
        ElMessage.warning('角色数据格式异常');
      }

      // 规范化角色数据，确保结构一致性
      filteredRoles.value = roleList.map(role => ({
        id: role?.id || null,
        nameZh: role?.nameZh || role?.name || '未知角色',
        name: role?.name || role?.nameZh || '未知角色',
        code: role?.code || '',
        description: role?.description || ''
      }));

      console.log('角色列表:', filteredRoles.value);
    } else {
      filteredRoles.value = [];
    }
  } catch (error) {
    console.error('搜索角色出错:', error);
    filteredRoles.value = [];
  } finally {
    roleLoading.value = false;
  }
};

const confirmAssignTask = async () => {
  if (!currentTaskForAssign.value.id) {
    ElMessage.error('任务ID不存在，无法分配角色');
    return;
  }

  if (!selectedRoleId.value || selectedRoleId.value.length === 0) {
    ElMessage.warning('请选择角色');
    return;
  }

  try {
    console.log('分配任务:', currentTaskForAssign.value.id, '给角色:', selectedRoleId.value);

    // 执行角色分配操作
    const assignPromises = selectedRoleId.value.map(roleId =>
        request.post(`/role/${roleId}/task/${currentTaskForAssign.value.id}`, {
          taskId: currentTaskForAssign.value.id
        })
    );

    await Promise.all(assignPromises);

    ElMessage.success("任务角色分配成功");

    // 强制刷新任务列表，确保数据更新
    await loadTasks(currentPage.value, pageSize.value, true);

    // 使用nextTick确保DOM更新完成
    await nextTick(() => {
      console.log('任务列表已更新，DOM已刷新');
    });

    assignTaskDialogVisible.value = false;
  } catch (error) {
    console.error('分配任务出错:', error);
    if (error.response && error.response.status === 400) {
      ElMessage.error('请求格式错误: ' + (error.response.data.message || '参数不正确'));
    } else {
      ElMessage.error('网络请求失败，请检查控制台日志');
    }
  }
};

// 标记任务为已完成
const markTaskCompleted = async (task) => {
  console.log('准备标记完成的任务信息:', task);
  if (task.completed) return;

  // 确保任务数据包含必要字段
  if (!task.id || (!task.hasValidRoles && (!task.roles || task.roles.length === 0))) {
    console.error('任务数据不完整或未分配角色:', task);
    ElMessage.error('任务未分配角色，无法标记完成');
    return;
  }

  try {
    // 支持多角色任务完成（使用第一个角色ID作为默认值）
    const roleId = task.roleId || (task.roles && task.roles.length > 0 ? task.roles[0]?.id : null);

    if (!roleId) {
      ElMessage.error('任务未分配角色，无法标记完成');
      return;
    }

    console.log('标记任务完成 - roleId:', roleId, 'taskId:', task.id);

    const res = await request.put(`/role/${roleId}/task/${task.id}/complete`, {
      taskId: task.id,
      completed: true
    });

    console.log('标记完成响应:', res);

    if (res.code === 200) {
      ElMessage.success("任务标记为已完成");
      await loadTasks(currentPage.value, pageSize.value, true);
    } else {
      ElMessage.error(res.message || '标记任务失败');
    }
  } catch (error) {
    console.error('标记任务出错:', error);
    if (error.response && error.response.status === 400) {
      ElMessage.error('请求格式错误: ' + (error.response.data.message || '参数不正确'));
    } else {
      ElMessage.error('网络请求失败，请检查控制台日志');
    }
  }
};

// 监听筛选条件变化
watch(taskFilter, () => {
  loadTasks(currentPage.value, pageSize.value);
});

// 分页相关方法
const handleSizeChange = (newSize) => {
  loadTasks(currentPage.value, newSize);
};

const handleCurrentChange = (newPage) => {
  loadTasks(newPage, pageSize.value);
};
</script>

<style scoped>
.task-manage h2 {
  margin-bottom: 16px;
}
.loading-state {
  text-align: center;
  padding: 20px;
  color: #999;
}
.empty-state {
  text-align: center;
  padding: 20px;
  color: #999;
}
</style>